package com.yss.system.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yss.common.core.domain.YssResponse;
import com.yss.common.core.enums.YssStatusEnum;
import com.yss.common.core.utils.uuid.IdUtils;
import com.yss.common.security.annotation.InnerAuth;
import com.yss.system.api.domain.SysRole;
import com.yss.system.api.domain.SysUser;
import com.yss.system.domain.SysRoleDept;
import com.yss.system.service.ISysRoleDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.yss.common.core.utils.StringUtils;
import com.yss.common.core.web.controller.BaseController;
import com.yss.common.core.web.domain.AjaxResult;
import com.yss.common.logger.annotation.Log;
import com.yss.common.logger.enums.BusinessType;
import com.yss.common.security.annotation.RequiresPermissions;
import com.yss.common.security.utils.SecurityUtils;
import com.yss.system.api.domain.SysDept;
import com.yss.system.service.ISysDeptService;

/**
 * 部门信息
 */
@RestController
@RequestMapping("/dept" )
public class SysDeptController extends BaseController {
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private ISysRoleDeptService roleDeptService;

    /**
     * 获取部门列表
     */
    @RequiresPermissions("system:dept:list" )
    @GetMapping("/list" )
    public AjaxResult list(SysDept dept) {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return success(depts);
    }

    /**
     * 查询部门列表（排除节点）
     */
    @RequiresPermissions("system:dept:list" )
    @GetMapping("/list/exclude/{deptId}" )
    public AjaxResult excludeChild(@PathVariable(value = "deptId" , required = false) String deptId) {
        SysDept dept = new SysDept();
        dept.setId(deptId);
        List<SysDept> depts = deptService.selectDeptList(dept);
        return success(depts);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @RequiresPermissions("system:dept:query" )
    @GetMapping(value = "/{deptId}" )
    public AjaxResult getInfo(@PathVariable String deptId) {
        deptService.checkDeptDataScope(deptId);
        return success(deptService.getById(deptId));
    }

    /**
     * 新增部门
     */
    @RequiresPermissions("system:dept:add" )
    @Log(title = "部门管理" , businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDept dept) {
        if (!deptService.checkDeptNameUnique(dept)) {
            return error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在" );
        }
        dept.setId(IdUtils.fastSimpleUUID());
        dept.setCreateBy(SecurityUtils.getUsername());
        dept.setCreateTime(new Date());
        return toAjax(deptService.insertDept(dept));
    }

    /**
     * 修改部门
     */
    @RequiresPermissions("system:dept:edit" )
    @Log(title = "部门管理" , businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysDept dept) {
        String deptId = dept.getId();
        deptService.checkDeptDataScope(deptId);
        if (!deptService.checkDeptNameUnique(dept)) {
            return error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在" );
        } else if (dept.getParentId().equals(deptId)) {
            return error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己" );
        } else if (YssStatusEnum.DELETED.getCode() == dept.getStatus() && deptService.selectNormalChildrenDeptById(deptId) > 0) {
            return error("该部门包含未停用的子部门！" );
        }
        dept.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(deptService.updateDept(dept));
    }

    /**
     * 删除部门
     */
    @RequiresPermissions("system:dept:remove" )
    @Log(title = "部门管理" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}" )
    public AjaxResult remove(@PathVariable String deptId) {
        if (deptService.hasChildByDeptId(deptId)) {
            return warn("存在下级部门,不允许删除" );
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return warn("部门存在用户,不允许删除" );
        }
        deptService.checkDeptDataScope(deptId);
        return toAjax(deptService.deleteDeptById(deptId));
    }


    /**
     * 获取用户所在部门 和下级部门，数据权限控制使用
     */
    @InnerAuth
    @PostMapping("/getUserDeptIds" )
    public YssResponse<List<String>> getUserDeptIds(@RequestBody SysUser sysUser) {
        List<String> list = deptService.queryDeptIds(sysUser.getDeptId());
        list.add(sysUser.getDeptId());
        return YssResponse.ok(list);
    }

    /**
     * 获取自定义的部门数据 list 数据权限控制使用
     */
    @InnerAuth
    @PostMapping("/getRoleDeptIds" )
    public YssResponse<List<String>> getRoleDeptIds(@RequestBody SysRole sysRole) {
        QueryWrapper<SysRoleDept> wrapper = new QueryWrapper<>();
        wrapper.eq("ROLE_ID" , sysRole.getId());
        List<SysRoleDept> list = roleDeptService.list(wrapper);
        List<String> deptIds = new ArrayList<>();
        if (!StringUtils.isNotEmpty(list)) {
            return YssResponse.ok(deptIds);
        }
        for (SysRoleDept dept : list) {
            deptIds.add(dept.getDeptId());
        }
        return YssResponse.ok(deptIds);
    }
}
